package initialize

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"service_base_shop/order_srv/global"
	"time"
)

func InitDB()  {
	MysqlConfig := global.ServerConfig.MysqlInfo
	fmt.Println(MysqlConfig)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",MysqlConfig.UserName,MysqlConfig.PassWord,MysqlConfig.Host,MysqlConfig.Prot,MysqlConfig.Name)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,   // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,         // 禁用彩色打印
		},
	)
	var err error
	global.DB , err = gorm.Open(mysql.Open(dsn),&gorm.Config{
		NamingStrategy: schema.NamingStrategy{   //表名称的约束
			SingularTable: true,    // 表名前缀，`User`表为`t_users`
			TablePrefix: MysqlConfig.Prefix, // 表名前缀，`User`表为`t_users`
		},
		Logger:newLogger,
	})
	if err != nil {
		panic(err)
	}
}
